<?php

namespace App\Services;


use App\Models\ElectricPaymentOrder;
use App\Models\ElectricPlatformAgent;
use App\Models\User;
use App\Models\Users;
use Illuminate\Support\Facades\DB;

class WechatPayService extends BaseService
{

    public function estatePay($param)
    {
        $user       = auth('user')->user();
        $openid     = $user->openid;
//        if (!empty($param['user_id'])) {
//            $user = User::query()->where('id', $param['user_id'])->first();
//        }

        $user_model = new Users();
        $user       = $user_model->getUserInfo($user->unionid);
        //获取用户信息--业主
        extract($param, null);
        /**
         * @var $fee_type |费用类型
         * @var $type |缴费类型
         * @var $paymentMoney |支付金额
         * @var $pay_type |支付方式
         * @var $device_type |设备类型
         */
        switch ($fee_type) {
            case 1:
                if (!isset($user['electric_id']) || $user['electric_id'] == 0) {
                    return $this->ApiError('您尚未绑定电表设备');
                }
                break;
            case 2:
                if (!isset($user['water_id']) || $user['water_id'] == 0) {
                    return $this->ApiError('您尚未绑定水表设备');
                }
                break;
            case 3:
                if (!isset($user['property_plan_id']) || $user['property_plan_id'] == 0) {
                    return $this->ApiError('您尚未匹配物业缴费方案，请联系管理员');
                }
                break;
        }
        $agent = ElectricPlatformAgent::where('id', $user['fatherId'])->select('level', 'split_type', 'wechat_account', 'sub_mch_id', 'rate', 'rate2')->first();
        if ($agent === null) {
            return $this->ApiError('代理商不存在');
        }
        [$handlingFee, $b1, $split_money, $b2] = $this->getNumbers($paymentMoney, $agent, $pay_type);
        if ($split_money <= 0) {
            return $this->ApiError(['code' => 2, 'msg' => '代理商设置有误']);
        }

        $order_arr = [
            'user_id'        => $user['id'],//业主id
            'feeType'        => $fee_type,//费用类型
            'type'           => $type,//缴费类型
            'paymentMoney'   => $paymentMoney,//支付金额
            'pay_type'       => $pay_type,//支付方式
            'orderNo'        => $this->uniqidNumberCode(12),//订单号
            'fatherId'       => $user['fatherId'],//代理商id
            'year'           => date('Y'),
            'month'          => date('m'),
            'day'            => date('d'),
            'split_money'    => $split_money,//分账金额
            'handlingFee'    => $handlingFee,//手续费
            'after_handling' => $b1,//去掉手续费
            'after_split'    => $b2,//再去调分账金额
            'device_type'    => $device_type,//设备类型
            'openid'         => $openid,
            'split_type'     => $agent['split_type'],//分账模式
        ];
        if (isset($param['months']) && $param['months'] != '') {
            $order_arr['months'] = $param['months'];
        }
        if (isset($param['is_instead']) && $param['is_instead'] == 2) {//他人代缴
            $order_arr['is_instead'] = $param['is_instead'];
        }

        try {
            $orderInsertId = ElectricPaymentOrder::query()->insertGetId($order_arr);
            if (in_array($order_arr['pay_type'], [1, 4])) {
                $options = ['orderId' => $orderInsertId, 'orderNo' => $order_arr['orderNo'], "agent" => $agent];
                $return_data = $this->doPay($options);//调起支付
            } else {
                $return_data = [];
            }

            $order_arr['order_id'] = $orderInsertId;
            $data                  = [
                'orderArr'    => $order_arr,//订单信息
                'return_Data' => $return_data//支付返回信息
            ];
            //发起支付
        } catch (\Exception $e) {
            Db::rollback();
            return $this->ApiError($e->getMessage());
        }
        Db::commit();
        return $this->format($data, '创建订单成功');
    }

    /**
     *获取费用数组
     * @param $paymentMoney |支付金额
     * @param $agent |代理商
     * @param $pay_type |支付方式
     * @return array
     */
    public function getNumbers($paymentMoney, $agent, $pay_type): array
    {
        $handlingFee = 0;
        $b1          = 0;
        $split_money = 0;
        $b2          = 0;

        switch ($agent['split_type']) {
            case 1://无分账
                $b1 = $b2 = $paymentMoney;
                break;
            case 2://自动分账
                $rate            = $agent['rate'];
                $wechat_discount = sprintf('%.3f', 0.006);//微信费率-------------------------------------------------------配置系统参数
                $handlingFee     = bcmul($paymentMoney, $wechat_discount, 2);  //手续费计算|(金额*微信费率)
                $b1              = bcsub($paymentMoney, $handlingFee, 2);      //去掉手续费 |(金额-手续费)
                if (isset($agent['else_discount']) && $agent['else_discount'] != 0) {
                    $else_handling = bcmul($paymentMoney, $agent['else_discount'], 2);//额外手续费计算，管理员可自行设置
                    $b1            = bcsub($b1, $else_handling, 2);
                }
                $split_money = bcmul($b1, $rate, 2);       //分帐金额 |(减去手续费金额*分账比例)
                $b2          = bcsub($b1, $split_money, 2);//分账完余额|(减去手续费金额-分账金额)
                break;
            case 3://手动分账
                $rate        = $agent['rate2'];
                $handlingFee = bcmul($paymentMoney, 0.001, 2);//手续费计算|(金额*微信费率)
                if ($pay_type === 3) {//如果支付宝手动分账【转款到支付宝账户，不需要手续费】@todo
                    $handlingFee = 0;
                }

                $b1          = bcsub($paymentMoney, $handlingFee, 2);//去掉手续费 |(金额-手续费)
                $split_money = bcmul($b1, $rate, 2);                 //分帐金额 |(减去手续费金额*分账比例)
                $b2          = bcsub($b1, $split_money, 2);          //分账完余额|(减去手续费金额-分账金额)
                break;
            default:
                break;
        }

        return array($handlingFee, $b1, $split_money, $b2);//再减去分账金额
    }

    /**
     * 唯一数字编码
     * @param integer $length
     * @return string
     */
    public function uniqidNumberCode($length = 10): string
    {
        $time = time() . '';
        if ($length < 10) $length = 10;
        $string = ($time[0] + $time[1]) . substr($time, 2) . rand(0, 9);
        while (strlen($string) < $length) $string .= rand(0, 9);
        return $string;
    }

    public function doPay($options)
    {
        $orderId = $options['orderId'];
        $orderNo = $options['orderNo'];
        $one_order = ElectricPaymentOrder::selectRaw('orderNo,paymentMoney,split_type,pay_type,is_instead,user_id')->get($orderId)->toArray();
        /**
         * @var $paymentMoney |支付金额
         * @var $split_type |分账模式
         * @var  |支付方式：1，小程序支付；2，公众号支付；3，支付宝支付；4，H5支付
         * @var $is_instead |是否为代付:1,否；2，是
         * @var $user_id |业主id
         *
         */
        if (empty($order)) {
            return $this->ApiError('暂无此订单');
        }
        $out_trade_no = $orderNo;//缴费订单号




    }
}
